// 极光IM
import JMessage from '@/utils/jmessage-wxapplet-sdk-1.4.3.min.js';
import md5 from '@/utils/md5.min.js'
let JIM = new JMessage({});
const store = {
	state: {
		appkey: '0f40e75520bc25436427464a',  // appKey
		secret: 'f55a543db14d264ca6c87da3',  // appSecret
		password: '022cd9fd995849b66666',    // password
		timestamp: Date.now(),               // 时间戳
		jimId: '',                           // 当前登录id
		isLoginJIM: false,
		isInitJIM: false,
	},
	getters: {
		// 随机字符串
		ranString: () => {
			let len = 20 + Math.floor(Math.random()*17);
			let str = 'abcdefghijklmnopqrstuvwxyz0123456789';
			let s = ''
			for(let i = 0; i < len; i++) {
				s += str.charAt(Math.floor(Math.random()*str.length));
			}
			return s;
		},

		// 请求签名
		signature: (state) => (ranstr) => {
			return md5(`appkey=${state.appkey}&timestamp=${state.timestamp}&random_str=${ranstr}&key=${state.secret}`);
		},

		// 获取极光id
		getJIMID: (state) => {
			if(!state.jimId) {
				state.jimId = uni.getStorageSync('jimId');
			}
			return state.jimId;
		}
	},
	mutations: {
		
		// 创建新的JIM
		createJIM(state) {
			console.log('创建新的JIM对象')
			JIM = new JMessage({});
		},

		// 设置极光id
		setJIMID (state, jimId) {
			state.jimId = jimId;
			uni.setStorage({
				key: 'jimId',
				data: jimId
			});
		},
		

	},
	actions: {

		// 初始化极光
		initJIM({state, getters}) {
			return new Promise((resolve, reject) => {
				let isConnect = JIM.isConnect();
				if(JIM.isInit()) {
					resolve({
						code: 0,
						event: "c_init",
						message: "success"
					});
				} else {
					const ranstr = getters.ranString;
					JIM.init({
						"appkey": state.appkey,
						"random_str": ranstr,
						"signature": getters.signature(ranstr),
						"timestamp": state.timestamp,
						"flag": 1
					}).onSuccess(data => { 
						state.isInitJIM = true;
						resolve(data);
					}).onFail(data => {
						state.isInitJIM = false;
						reject(data);
					}).onTimeout(data => {
						state.isInitJIM = false;
						console.log('初始化超时');
						reject(data);
					})
					// .onAck(data => {
					// 	state.isInitJIM = false;
					// 	console.log('初始化完成');
					// 	reject(data);
					// });
				}
			})
		},

		// 登录极光
		loginJIM({state}, args) {
			return new Promise((resolve, reject) => {
				let username = state.jimId;
				let password = state.password;
				if(args) {
					if(typeof args === 'string') {
						username = args;
					} else if(typeof args == 'object') {
						username = args.username || state.jimId;
						password = args.password || state.password;
					}
				}
				if(username) {
					JIM.login({
						username,
						password
					}).onSuccess(function(data) {
						state.isLoginJIM = true;
						resolve(data);
					}).onFail(function(data){
						state.isLoginJIM = false;
						reject(data);
					});
				}	else{
					state.isLoginJIM = false;
					reject('无登录用户id');
				}
			})
		},

		// 退出极光
		logoutJIM({state}) {
			JIM.loginOut();
			state.isLoginJIM = false;
		},

		// 获取资源原地址
		getUrlJIM({state}, id) {
			return new Promise((resolve, reject) => {
				JIM.getResource({
					'media_id' : id,
				}).onSuccess(function(data) {
					resolve(data.url);
				}).onFail(function(data) {
					reject(data);
				});
		 });
		},
		
		
		// 设置极光监听
		async setJIMJianTing({state, dispatch}) {
			console.log('创建新的JIM监听')
			// 极光断开连接重连
			JIM.onDisconnect(async () => {
				await dispatch('initJIM');
				await dispatch('loginJIM');
			});
			
			// 极光全局监听接收消息
			JIM.onMsgReceive(data => {
				console.log('接收到消息');
				let d = data.messages[0].content;
				// #ifdef APP-PLUS
				var options = {
					cover: true, // 是否覆盖上一条消息
					delay: 0,   // 延时显示
					title: '您有新消息了^_^'
				};
				let title = '[新消息]';
				let msg = {
				  message: d.msg_body.text,
				  messagetype: d.msg_type == 'text' ? 1 : d.msg_type == 'image' ? 2 : 3,
				};
				if (d.msg_body.extras) {
				  msg.extras = JSON.parse(d.msg_body.extras.extras);
				}
				if (msg.messagetype == 1) {
				  if (msg.extras && msg.extras.ad_info) {
				    title = '[位置]';
				  } else {
				    let txt = msg.message.replace(/(<\/?[^>]+>)|(\s)/g, '').slice(0, 15);
				    title = txt || '[新消息]';
				  }
				} else if (msg.messagetype == 2) {
				  title = '[图片]';
				} else if (msg.messagetype == 3) {
				  title = '[语音]';
				} else if(msg.messagetype == 4) {
					title = '[位置]';
				}
				
				let datas = {
					friendid: d.target_id,
					userid: d.from_id
				};
				if(this.getJIMID != datas.userid) {
					datas = JSON.stringify(datas);
					
					let routes = getCurrentPages();
					let currentPage = routes[routes.length - 1];
					let curRoute = currentPage.route;
					if(curRoute != 'pages/message/chat/chat') {
						plus.push.createMessage(title, datas, options);
					}
					uni.$emit('addChatMsg');
					
					// var mp3 = uni.createInnerAudioContext();
					// mp3.autoplay = true;
					// mp3.src = '/static/tishi.mp3';
					// mp3.play();
				}
				// #endif
				
				// 接受在线消息
				uni.$emit('jieShouChatMsg', d)
			});
			
			// #ifdef APP-PLUS
			// 点击通知栏
			plus.push.addEventListener('click', msg => {
				if (msg.payload) {
					let d = JSON.parse(msg.payload);
					let routes = getCurrentPages();
					let currentPage = routes[routes.length - 1];
					let curRoute = currentPage.route;
					if(curRoute == 'pages/message/chat/chat') {
						uni.redirectTo({
							url: '/pages/message/chat/chat?id='+d.userid
						})
					} else {
						uni.navigateTo({ 
							url: '/pages/message/chat/chat?id='+d.userid
						})
					}
				}
			})
			// #endif
		}
	}
}
export default store;
